#!/usr/bin/env node
import process from 'node:process';
import {Server} from 'socket.io';

import createServer from './createServer.mjs';
import createAppHandler from './createAppHandler.mjs';
import createChat from './createChat.mjs';

const {PORT, KEY, CERT, SYNC_DIR, SYNC_INTERVAL} = process.env;
const port = parseInt(PORT, 10) || 8000;
const syncDir = SYNC_DIR || '.data';
const syncInterval = parseInt(SYNC_INTERVAL, 10) || 15000;

// create server
let server;
try {
  server = createServer(KEY, CERT);
} catch (err) {
  process.stderr.write(err);
  process.stderr.write('\n');
  process.exit(1);
}

// serve static
const appHandler = createAppHandler();
server.on('request', appHandler);

// chat socket
const io = new Server(server);
const cleanUpChat = createChat(io, syncDir, syncInterval);

// start listening
console.log(`Start listening on port ${port}`);
server.listen(port);

// clean up
const cleanUp = async () => {
  await cleanUpChat();
  process.exit(0);
};
process.once('SIGINT', cleanUp);
process.once('SIGTERM', cleanUp);
